package com.gzsxy.esjy.service.netty.util;


import com.gzsxy.esjy.service.netty.fileServer.configure.ServerStaticProperties;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * 文件操作类
 * @author zhangxiaolong
 * @date 2022/7/11 9:36
 */
public class FileUtils {
	
	
	private final static int parts = 50 ;
	
	/**
	 * 保存byte 文件
	 * @param bytes
	 * @param dir /../../
	 * @param name xxx.xxx
	 * @return dir + name
	 * @throws Exception
	 */
	public static String createFileOfByte(byte[] bytes,String dir,String name) throws Exception {
		if(mkdirs(dir)) {
			String fullPath = dir + name ;
			OutputStream out = null ;
			try {
				 out = new FileOutputStream(fullPath) ;
				 out.write(bytes);
				 out.flush();
				 return fullPath ;
			}finally {
				close(out);
			}
		}
		return null ;
	}
	/**
	 * 保存文件
	 * @param bytes
	 * @param fullPath
	 * @return
	 * @throws Exception
	 */
	public static String createFileOfByte(byte[] bytes,String fullPath) throws Exception {
		OutputStream out = null ;
		try {
			out = new FileOutputStream(fullPath) ;
			out.write(bytes);
			out.flush();
			return fullPath ;
		}finally {
			close(out);
		}
	}
	
	/**
	 * 创建目录
	 * @param dir
	 * @return
	 */
	public static boolean mkdirs(String dir) {
		File dirF = new File(dir);
		if(!dirF.exists()) {
			return  dirF.mkdirs() ;
		}
		return true ;
	}
	
	/**
	 * 文件删除
	 * @param path
	 * @return
	 */
	public static boolean deleteFile(String path) {
		File file = new File(path) ;
		File parentFile = file.getParentFile();
		file.delete() ;
		if(parentFile.list().length == 0) {
			return deleteFile(parentFile.getPath()) ;
		}
		return true ;
	}
	
	/**
	 * 获取文件真实路径
	 * @param fileName
	 * @return
	 */
	public static String getFilePath(String baseDir, String fileName) {
		if(baseDir == null) {
			baseDir = "" ;
		}else {
			if(!baseDir.endsWith("/")) {
				baseDir +="/" ;
			}
			if(baseDir.startsWith("/")) {
				baseDir = baseDir.substring(1) ;
			}
		}
		int hashCode = fileName.hashCode();
		String dir = baseDir+hashCode % parts+"/" ;
		File file = new File(ServerStaticProperties.RESOURCES_ROOT+dir) ;
		if(!file.exists()) {
			file.mkdirs() ;
		}
		return dir+fileName ;
	}

	/**
	 * 关闭流
	 * @param args
	 */
	public static void close(Closeable ...args) {
		for (Closeable closeable : args) {
			try {
				if(closeable != null) {
					closeable.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}
